package me.huanmeng.heater.console;

import lombok.Getter;
import me.huanmeng.heater.Heater;
import me.huanmeng.heater.main.HeaterMain;
import net.minecrell.terminalconsole.SimpleTerminalConsole;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.io.IoBuilder;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;

import java.util.logging.Handler;
import java.util.logging.Logger;

/**
 * 2021/9/26<br>
 * Heater<br>
 * 控制台
 *
 * @author huanmeng_qwq
 */
public class BotConsole extends SimpleTerminalConsole {
    @Getter
    private Logger logger;

    public BotConsole() {
        init();
        if (HeaterMain.getInstance().isDebug()) {
            System.out.println("Debug was enable.");
        }
    }

    void init() {
        logger = genLogger();
    }

    static Logger genLogger() {
        org.apache.logging.log4j.Logger logger = LogManager.getRootLogger();
        System.setErr(IoBuilder.forLogger(logger).setLevel(Level.ERROR).buildPrintStream());
        System.setOut(IoBuilder.forLogger(logger).setLevel(Level.INFO).buildPrintStream());
        Logger log = Logger.getLogger("");
        for (Handler handler : log.getHandlers()) {
            log.removeHandler(handler);
        }
        log.setLevel(java.util.logging.Level.ALL);
        log.addHandler(new LogHandler());
        log.setUseParentHandlers(false);
        return Logger.getLogger("Heater");
    }

    @Override
    protected LineReader buildReader(LineReaderBuilder builder) {
        return super.buildReader(builder
                .appName(Heater.getName())
        );
    }

    @Override
    protected boolean isRunning() {
        return HeaterMain.getInstance().isRunning();
    }

    @Override
    protected void processInput(String input) {
        String command = input.trim();
        runCommand(command);
    }

    @Override
    protected void runCommand(String s) {
        System.out.println("execute Command: " + s);
        if (s.equals("stop")) {
            shutdown();
        } else if (s.equals("relogin")) {
            try {
                HeaterMain.getInstance().getBot().logout();
                ;
                System.out.println("wait 10s");
                Thread.sleep(1000 * 10);
                HeaterMain.getInstance().getBot().login();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void shutdown() {
        HeaterMain.getInstance().stop();
    }
}
